home *** CD-ROM | disk | FTP | other *** search
- Path: hubcap.clemson.edu!hubcap!mjs
- From: mjs@hubcap.clemson.edu (M. J. Saltzman)
- Newsgroups: comp.lang.c
- Subject: Re: Convert a float to an int ( and round up/down ? )
- Date: 7 Mar 96 16:21:03 GMT
- Organization: Clemson University
- Message-ID: <mjs.826215663@hubcap>
- References: <826162763.17141@farlight.demon.co.uk>
- NNTP-Posting-Host: hubcap.clemson.edu
- X-Newsreader: NN version 6.5.0 #1
-
- j shipley <jonathan@farlight.demon.co.uk> writes:
-
- >I am trying to convert a variable of type float to an int.
-
- You need to be more specific about what you mean here. (See below.)
-
- >How can this be done?
-
- >I have tried (int) variable
- >i.e what I thought a cast was, but it does not work.
-
- A cast converts the *value* of a variable (or expression) to a new
- type, changing the representation if necessary (the float-to-int cast
- throws away the fractional part of the float and converts what's left
- to an int). It does not reinterpret the bits stored in the variable.
- If reinterpreting the bits is your goal, you might be able to use a
- union or something like
-
- float x = 1.0;
- int i = *(int *) &x;
-
- in your compiler, but the result is not portable (in fact it's
- undefined). Better would be to redesign your program so that you
- don't need to do this.
-
- >Part 2:
-
- >Can I round a float up/down to the nearest number?
-
- #define ROUND(x) ((int) ((x) >= 0.0 ? (x) + 0.5 : (x) - 0.5)
-
- If you want anything other than rounding away from zero when the fractional
- part is exactly 0.5, then you have to write something more sophisticated.
-
- >Does a cast do the same as using the modulus operator, %? (in this case).
-
- No. A cast from float to int discards the fractional part (truncating
- toward zero). The modulus operator produces the integer remainder
- after an integer division, e.g. 14 / 3 == 4, 14 % 3 == 2. (A
- floating-point version is provided by the math.h function fmod().) If
- you want the fractional part of a float, #include <math.h> and use the
- modf() function, or use
-
- float frac = x - (int) x;
-
- if you are sure that the integer part of x will fit in an int.
-
- >I am using Borland C 3.1, and A Book On C (Kelly/Pohl) - neither of which
- >has informed me.
-
- >Thanks for your help.
-
- --
- Matthew Saltzman
- Clemson University Math Sciences
- mjs@clemson.edu
-